package server;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import iface.Envelope;
import iface.Heartbeat;
import iface.MessageInterface;
import iface.Status;

public class ServerHeartbeat {

    private static final int SLEEP = 30; // sec
    private static final String GROUP_EMAIL = "cse403h@cs.washington.edu";
    private static int MAX_FAILURES = 2;

    public static void main(String[] args) throws Exception {

        Envelope env = new Envelope("heartbeat", new Heartbeat());
        int failures = 0;
        boolean broken = false;

        while (true) {
            Status status = MessageInterface.sendEnvelopeToServer(env);
            if (!status.getMessageStatus().equals(Status.Result.SUCCESS)) {
                failures++;
                System.out.println("Uh oh, consecutive failure number "
                        + failures);
                if (failures >= MAX_FAILURES && !broken) {
                    handleServerDown();
                    broken = true;
                }
            } else {
                // The server is alive and kicking still!
                System.out.println("Server is alive!");
                broken = false;
                failures = 0;
            }

            try {
                Thread.sleep(SLEEP * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /*
     * Email our cse403 group email that the server is down and must be
     * restarted and investigated.
     */
    private static void handleServerDown() throws Exception {
        String smtpServer, to, from, subject, body;
        smtpServer = "";
        to = GROUP_EMAIL;
        from = "client665@gmail.com";
        subject = "Oh no! The HvZServer is down!";
        body = "The HvZServer did not respond to a heartbeat message, this "
                + "probably means the server is down for some reason. Someone "
                + "should look at the server log file.";
        send(smtpServer, to, from, subject, body);
    }

    private static void send(String smtpServer, String to, String from,
            String subject, String body) throws Exception {
        String smtpHostName = "smtp.gmail.com";
        int smtpHostPort = 465;
        String smtpAuthUser = "client665@gmail.com";
        String smtpAuthPwd = "password665";

        Properties props = new Properties();

        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtps.host", smtpHostName);
        props.put("mail.smtps.auth", "true");

        Session mailSession = Session.getDefaultInstance(props);
        mailSession.setDebug(false);
        Transport txport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(subject);
        message.setContent(body, "text/plain");

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        txport.connect(smtpHostName, smtpHostPort, smtpAuthUser, smtpAuthPwd);

        txport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
        txport.close();
        System.out.println("Sent server down email!");
    }

}
